<?php namespace Common\Model;
use Hdphp\Model\Model;
class Goods extends Model{
	protected $table = 'goods';
//	自动完成
	protected $validate = array(
//		分类名不能为空
		array('gname','required','商品名不能为空',3,3),
		array('gname','maxlen:200','商品名不能超过200个字符',3,3),
		array('category_cid','required','请选择商品分类',3,3),
		array('brand_bid','required','请选择商品品牌',3,3),
		array('unit','required','计量单位不能为空',3,3),
		array('mprice','required','市场价不能为空',3,3),
		array('sprice','required','商城价不能为空',3,3),
		array('listpic','required','商品列表图未上传',3,3),
		array('content','required','商品详情内容不能为空',3,3),
//		价格范围
		array('mprice','num:0,9999999','排序范围：0~9999999',3,3),
		array('sprice','num:0,9999999','排序范围：0~9999999',3,3),
	);
//	自动完成
	protected $auto = array(
		array('addtime','time','function',3,1),
	);
//	商品添加
	public function store(){
		if(!$this->create()) return false;
		
//		1.商品表添加的类容
//		admin_aid管理员id
		$this->data['admin_aid'] = $_SESSION['aid'];
//		类型id
		$cateModel = new \Common\Model\Category;
		$cid = Q('post.category_cid',0,'intval');
		$this->data['type_tid'] = $cateModel->where("cid = {$cid}")->pluck('type_tid');
//		列表图的处理
		$listpic = Q('post.listpic');
		$type = strrchr($listpic, '.');
		$newlistpic = str_replace($type, '_listpic'.$type, $listpic);
		$this->data['listpic'] = Image::thumb($listpic,$newlistpic,240,240,2);
		unlink($listpic);
//		商品货号生成
		$temp = 'qwertyiopasdfghjklzxcvbnm1234567890';
//		生成16位货号
		static $gnum = '';
		for ($i=0; $i < 16; $i++) { 
			$j = mt_rand(0, strlen($temp)-1);
			$gnum = $gnum . $temp[$j];
		}
		$this->data['gnumber'] = $gnum;

		
//		添加商品表并接受返回的gid接受gid
		$gid = $this->add();
		
		
//		2.商品详情添加
//		获得图片类型
//		图片路径
		$pathlist = Q('post.thumb');
		$mini = array();
		$medium = array();
		$big = array();
//		判断是否有商品图片上传
		if(!$pathlist){
			$this->error = '请上传商品图片';
			return false;
		}
		foreach ($pathlist as $k => $v) {
			$type = strrchr($v, '.');
//			小图保存路径
			$miniPath = str_replace($type, '_mini'. $type, $v);
			$mini[] = Image::thumb($v,$miniPath,60,60,2);
//			中图路径
			$medPath = str_replace($type, '_medium'. $type, $v);
			$medium[] = Image::thumb($v,$medPath,480,480,2);
//			大图路径
			$bigPath = str_replace($type, '_big'. $type, $v);
			$big[] = Image::thumb($v,$bigPath,1000,1000,2);
//			删除原图
			if(is_file($v)){
				unlink($v);
			}
		}
//		组合商品详细表需要的数组
		$gdetail = array(
			'mini'=>implode(',', $mini),
			'medium'=>implode(',', $medium),
			'big' =>implode(',', $big),
			'content'=>Q('post.content'),
			'goods_gid'=>$gid,
		);
		$gdModel = new \Common\Model\Gdetail;
		if(!$gdModel->store($gdetail)){
			$this->error = $gdModel->getError();
			return false;
		} 
		
//		商品属性表
		$gattrModel = new \Common\Model\Gattr;
//		获得属性值
		$attr = Q('post.attr');
		if($attr){
			foreach ($attr as $k => $v) {
				foreach ($v['value'] as $kk => $vv) {
					$tmp = array(
						'gavalue'=>$vv,
						'addprice'=>0,
						'attribute_atid'=>$k,
						'goods_gid'=>$gid,
					);
					if(!$gattrModel->store($tmp)){
						$this->error = $gattrModel->getError();
						return false;
					}
				}
			}
		}
		
//		获得规格值
		$spec = Q('post.spec');
		if($spec){
			foreach ($spec as $k => $v) {
				foreach ($v['value'] as $kk => $vv) {
					$tmp = array(
						'gavalue'=>$vv,
						'addprice'=>$v['price'][$kk],
						'attribute_atid'=>$k,
						'goods_gid'=>$gid,
					);
					if(!$gattrModel->store($tmp)){
						$this->error = $gattrModel->getError();
						return false;
					}
				}
			}
		}else{
//			留着写填写规格的错误反馈
		}
		
		
//		所有添加成功后返回真
		return true;
	}
	
//	商品编辑
	public function edit(){
		if(!$this->create()) return false;
		$glModel = new \Common\Model\Glist;
//		1.商品表修改的类容
//		商品id
		$gid = Q('post.gid',0,'intval');
//		获得原列表图地址
		$oldlistpic = $this->where("gid = {$gid}")->pluck('listpic');
		if(Q('post.listpic')!=$oldlistpic){
			unlink($oldlistpic);
			$listpic = Q('post.listpic');
			$type = strrchr($listpic, '.');
			$newlistpic = str_replace($type, '_listpic'.$type, $listpic);
			$this->data['listpic'] = Image::thumb($listpic,$newlistpic,240,240,2);
			unlink($listpic);
		}
//		admin_aid管理员id
		$this->data['admin_aid'] = $_SESSION['aid'];
		
//		类型id
		$cateModel = new \Common\Model\Category;
		$cid = Q('post.category_cid',0,'intval');
		$this->data['type_tid'] = $cateModel->where("cid = {$cid}")->pluck('type_tid');
//		添加商品表并接受返回的gid接受gid
		
//		如果更改类型，则需要将货品表清空，并将总库存变为0
//		获得该商品表中的category_cid
		$oldcid = $this->where("gid = {$gid}")->pluck('category_cid');
		if($cid != $oldcid){
//			清空货品表
			
			$glModel->where("goods_gid = {$gid}")->delete();
			$this->data['inventory'] = 0;
		}
		
		$this->save();
		
//		2.商品详情修改
//		商品详情id
		$gdModel = new \Common\Model\Gdetail;
		$gdid = $gdModel->where("goods_gid = {$gid}")->pluck("gdid");
		$gdData = $gdModel->where("goods_gid = {$gid}")->find();
		$gdData['mini'] = explode(',', $gdData['mini']);
		$gdData['medium'] = explode(',', $gdData['medium']);
		$gdData['big'] = explode(',', $gdData['big']);
//		图片路径
		$pathlist = Q('post.thumb');
		$mini = array();
		$medium = array();
		$big = array();
//		判断是否有商品图片上传
		if(!$pathlist){
			$this->error = '请上传商品图片';
			return false;
		}
		
//		循环原数据库的内容进行比对，有则添加，无则删除
		foreach ($gdData['medium'] as $kk => $vv) {
			if(!in_array($vv, $pathlist)){
				$miniPath = str_replace('_medium', '_mini', $vv);
				$bigPath = str_replace('_medium', '_big', $vv);
				unlink($miniPath);
				unlink($vv);
				unlink($bigPath);
			}
		}
		
		
		foreach ($pathlist as $k => $v) {
			$type = strrchr($v, '.');
//			获取格式的长度
			$typelen = strlen($type);
//			截取特定字符串进行判断
			$oldPath = substr($v, -($typelen+7),-$typelen);			
			
			if($oldPath =='_medium'){//如果该图已经存在
				$mini[] = str_replace('_medium'.$type, '_mini'.$type, $v);
				$medium[] = $v;
				$big[] = str_replace('_medium'.$type, '_big'.$type, $v);
			}else{//如果是新添加的
	//			小图保存路径
				$miniPath = str_replace($type, '_mini'. $type, $v);
				$mini[] = Image::thumb($v,$miniPath,60,60,2);
	//			中图路径
				$medPath = str_replace($type, '_medium'. $type, $v);
				$medium[] = Image::thumb($v,$medPath,480,480,2);
	//			大图路径
				$bigPath = str_replace($type, '_big'. $type, $v);
				$big[] = Image::thumb($v,$bigPath,1000,1000,2);
	//			删除原图
				if(is_file($v)){
					unlink($v);
				}
			}
		}
		
		
		
		
		//		组合商品详细表需要的数组
		$gdetail = array(
			'gdid'=>$gdid,
			'mini'=>implode(',', $mini),
			'medium'=>implode(',', $medium),
			'big' =>implode(',', $big),
			'content'=>Q('post.content'),
			'goods_gid'=>$gid,
		);
		if(!$gdModel->edit($gdetail)){
			$this->error = $gdModel->getError();
			return false;
		} 
		
		
		
				
//		修改商品属性表
		$gattrModel = new \Common\Model\Gattr;
		
		
//		获得规格值
		$spec = Q('post.spec');
//		获得属性值
		$attr = Q('post.attr');
//		获得所有提交的属性或者规格的值
		$temp = array();
		if($spec){
			foreach ($spec as $k => $v) {
				foreach ($v['value'] as $kk => $vv) {
					$temp[] = $vv;
				}
			}
		}
		if($attr){
			foreach ($attr as $k => $v) {
				foreach ($v['value'] as $kk => $vv) {
					$temp[] = $vv;
				}
			}
		}
//		得到原商品属性表中的旧数据
		$oldgattr = $gattrModel->where("goods_gid = {$gid}")->get();
//		定义一个空数组接受被删除了的规格id
		$specDel = array();
		foreach ($oldgattr as $k => $v) {
			if(!in_array($v['gavalue'], $temp)){
				$specDel[] = $v['gaid'];
				$gattrModel->where("gaid = {$v['gaid']}")->delete();
			}
		}
		
		$glData = $glModel->where("goods_gid = {$gid}")->get();
		foreach ($glData as $k => $v) {
			$glData[$k]['combine'] = explode(',', $v['combine']);
		}
		
//		定义一个变量用来接收被删掉的库存，用于改变总库存
		$total = 0;
		foreach ($glData as $k => $v) {
			foreach ($v['combine'] as $kk => $vv) {
				if(in_array($vv, $specDel)){
					$glid = $v['glid'];
					$total = $total + $glModel->where("glid = {$glid}")->pluck('inventory');
//					删除对应货品组合
					$glModel->where("glid = {$glid}")->delete();
				}
			}
		}
		
		if($total != 0){
			$total = $this->where("gid = {$gid}")->pluck('inventory') - $total;
			$tmp = array(
				'gid'=>$gid,
				'inventory'=>$total,
			);
			$this->save($tmp);
		}
		
		
		/*
		 * 好饿，吃了饭再来进行非清空更新*/
		$oldgattr = $gattrModel->where("goods_gid = {$gid}")->get();
		$temp = array();
		foreach ($oldgattr as $k => $v) {
			$temp[] = $v['gavalue'];
		}
		
		
		
		if($attr){
			foreach ($attr as $k => $v) {
				foreach ($v['value'] as $kk => $vv) {
					if(!in_array($vv, $temp)){
						$tmp = array(
						'gavalue'=>$vv,
						'addprice'=>0,
						'attribute_atid'=>$k,
						'goods_gid'=>$gid,
						);
						if(!$gattrModel->edit($tmp)){
							$this->error = $gattrModel->getError();
							return false;
						}
					}
				}
			}
		}
		
		
		if($spec){
			foreach ($spec as $k => $v) {
				foreach ($v['value'] as $kk => $vv) {
					if(!in_array($vv, $temp)){
						$tmp = array(
							'gavalue'=>$vv,
							'addprice'=>$v['price'][$kk],
							'attribute_atid'=>$k,
							'goods_gid'=>$gid,
						);
						if(!$gattrModel->edit($tmp)){
							$this->error = $gattrModel->getError();
							return false;
						}
					}
					
				}
			}
		}else{
//			留着写填写规格的错误反馈
		}
		
		return true;
//		p($_POST);die;
	}
	
	
	
}
 ?>